
import BaseSDK from "./BaseSdk"
import SDKEvent from "./SDKEvent";

// const eventTarget = new cc.EventTarget();

export default class WXSDK extends BaseSDK {

    private static _instance: WXSDK = null;
    public static get Instance(): WXSDK {
        this._instance = this._instance || new WXSDK();
        return this._instance;
    }

    private _recorderShareFunc = null;

    private _musicPauseFunc = null;
    private _musicPauseThis = null;
    private _musicResumeFunc = null;
    private _musicResumeThis = null;
    private _clipboardData = "";

    private _playScreenTime = 0;
    private _screenSpaceTime = 0;
    private _interstitiaId = "";
    private _moreGameBtn = null;

    private _recorder = null;//录屏器
    private lastAdTime = 0;//最后一次插屏播放时间
    private _recorderStatus = 0;
    private _recorderEndTime = 0;
    private _recorderTime = 0;

    private _videoId = "";
    private _gridId = ""; //5个格子
    private _bannerId = "";
    private _screenId = "";

    private _shareId = "";
    private _shareUrl = "";
    private _shareTitle = "一起来动脑";
    private _shareDesc = "眼疾手也要快";
    protected _shareOptions = null;

    private _videoLoaded = false;
    private _videoOptions = null;
    private _videoAd = null;
    private _interstitiaAd = null;
    private screenShow: boolean = false;//插屏是否显示
    private _bannerLoaded = false;
    private gridAd = null;
    private banner = null;
    private lastshockTime = 0;//最后震动时间
    private shareBtn = null;//分享按钮
    private shareValue: number = 1;
    private _shakeState: boolean; //震动的状态

    init() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        this._shakeState = false;
        let that = this;
        this.lastAdTime = new Date().getTime();
        this.showShareMenu(true);
        globalThis.wx.onShareAppMessage(this.shareAppMessageCallback.bind(this));
        globalThis.wx.onShow((res) => {
            console.log("********游戏回到前台************", res);
        });
        this.checkNewVersion();
        this.setKeepScreenOn({ keepScreenOn: true });

        that._preloadVideo();
        that._loadBanner();
        that._loadGrid();

        // this._recorder = wx.getGameRecorder();
        // if(this._recorder.isFrameSupported()){
        //     this._recorder.on('start', () => {
        //         that._recorderTime=new Date().getTime();
        //         that._recorderStatus=1;
        //         console.log("录屏开始",that._recorderTime);
        //     })
        //     this._recorder.on('stop', (res) => {
        //         that._recorderStatus=0;
        //         that._recorderEndTime=new Date().getTime();
        //         console.log(`对局回放时长: ${res.duration}`)
        //     })
        // }
        // let { windowWidth, windowHeight } = wx.getSystemInfoSync();
        // this.shareBtn=wx.createGameRecorderShareButton({
        //     style:{
        //         left:100,
        //         top:windowHeight - 250,
        //         height:60,
        //         fontSize:22,
        //         text:"分享游戏时刻"
        //     },
        //     share:{
        //         bgm:"",
        //         timeRange:[[0,30000]]
        //     }
        // });
        // this.shareBtn.onTap((res)=>{
        //     console.log("调用录屏分享失败",res);
        // });
        // this.shareBtn.hide();
    }

    //检查版本更新
    public checkNewVersion() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        let updateManager = globalThis.wx.getUpdateManager();
        if (!updateManager) return;
        // 获取全局唯一的版本更新管理器，用于管理小程序更新
        updateManager.onCheckForUpdate((res) => {
            // 监听向微信后台请求检查更新结果事件 
            console.log("是否有新版本：" + res.hasUpdate);
            if (res.hasUpdate) {
                //如果有新版本                
                // 小程序有新版本，会主动触发下载操作        
                updateManager.onUpdateReady(() => {
                    //当新版本下载完成，会进行回调          
                    globalThis.wx.showModal({
                        title: '更新提示',
                        content: '新版本已经准备好，单击确定重启小程序',
                        showCancel: false,
                        success: (res) => {
                            if (res.confirm) {
                                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序               
                                updateManager.applyUpdate();
                            }
                        }
                    })
                })
                // 小程序有新版本，会主动触发下载操作（无需开发者触发）        
                updateManager.onUpdateFailed(() => {
                    //当新版本下载失败，会进行回调          
                    globalThis.wx.showModal({
                        title: '提示',
                        content: '检查到有新版本，但下载失败，请稍后尝试',
                        showCancel: false,
                    })
                })
            }
        });

    }

    //显示转发按钮
    private showShareMenu(bool: boolean) {
        if (bool) {
            globalThis.wx.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            })
        } else {
            globalThis.wx.showShareMenu({ withShareTicket: false });//设置分享按钮，
        }
    }

    public share(options: { success?: Function, fail?: Function }) {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        this._shareOptions = options;
        globalThis.wx.shareAppMessage(options);
    }

    private shareAppMessageCallback() {
        let data = this.getShareConfig();
        return {
            title: data.title,
            imageUrl: data.url,
            imageUrlId: data.id,
            query: "key1=val1&key2=val2",
            success: () => {
                console.log("分享成功");
                this._shareOptions && this._shareOptions.success && this._shareOptions.success();
            },
            fail: (e) => {
                console.log("分享失败");
                this._shareOptions && this._shareOptions.fail && this._shareOptions.fail();
            }
        }
    }

    private getShareConfig() {
        let data = { url: null, id: "", title: "" };
        switch (this.shareValue) {
            case 1:
                data.id = this._shareId;
                data.url = this._shareUrl;
                break;
            case 2:
                //本地分享,需要配置本地图片
                // let ran = Tools.getRandomInt(0, GameConfig.Instance.shares.length - 1);
                // data.url = GameConfig.Instance.shares[ran].nativeUrl
                break;
            case 3:
                let canvas = globalThis.wx.createCanvas();
                data.url = canvas.toTempFilePathSync({
                    destWidth: 500,
                    destHeight: 400
                })
                break;
            default:
                data = { url: null, id: "", title: "" };
        }
        data.title = this._shareTitle;
        return data;
    }


    //预载视频广告
    private _preloadVideo() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        if (!this._videoId) {
            return
        }
        let that = this;
        //视频广告
        this._videoAd = globalThis.wx.createRewardedVideoAd({ adUnitId: that._videoId });
        this._videoAd.onLoad(res => {
            that._videoLoaded = true;
            console.log("广告加载成功onLoad");
        });
        this._videoAd.load().then(() => {
            console.log("广告加载成功");
            that._videoLoaded = true;
        });
        this._videoAd.onClose(res => {
            that._videoLoaded = false;
            that.lastAdTime = new Date().getTime();
            if (res.isEnded) {
                that._videoOptions && that._videoOptions.success && that._videoOptions.success();
            } else {
                that._videoOptions && that._videoOptions.fail && that._videoOptions.fail();
                // globalThis.wx.showModal({
                //     title: "奖励提醒",
                //     content: "中途关闭视频无法获得奖励，是否继续获得奖励？",
                //     success(res) {
                //         console.log(res);
                //         if (res.confirm) {
                //             that.showRewardVideo(that._videoOptions);
                //         } else if (res.cancel) {

                //         } else {

                //         }
                //     },
                //     fail(res) {
                //         console.log(`showModal调用失败`);
                //     },
                // });
            }
            that._videoAd.load().then(() => {
                console.log("广告关闭后重新加载成功");
                that._videoLoaded = true;
            });
        });
        this._videoAd.onError(res => {
            that._videoLoaded = false;
            console.log("加载失败，尝试重试");
            setTimeout(() => {
                that._videoAd.load().then(() => {
                    that._videoLoaded = true;
                });
            }, 10000);
        });
    }

    private _loadBanner() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        if (!this._bannerId) {
            return
        }
        let that = this;
        if (this.banner) {
            this.banner.destroy();
            this.banner = null;
        }
        const { windowWidth, windowHeight } = globalThis.wx.getSystemInfoSync();
        const targetBannerAdWidth = 350;
        const targetBannerAdHeight = 100;
        // 创建一个居于屏幕底部正中的广告
        this.banner = globalThis.wx.createBannerAd({
            adUnitId: that._bannerId,
            style: {
                width: targetBannerAdWidth,
                height: targetBannerAdHeight,
                left: (windowWidth - targetBannerAdWidth) / 2,
                top: windowHeight - windowHeight * 0.2,
            },
        });
        this.banner.onLoad(() => {
            that._bannerLoaded = true;
            setTimeout(() => {
                that._loadBanner();
            }, 60000);
        });
        this.banner.onError(() => {
            that._bannerLoaded = false;
            this._loadGrid();
        });
        this.banner.onResize((size) => {
            // console.log(size.width, windowWidth, size.height, windowHeight);
            that.banner.style.left = (windowWidth - size.width) / 2;
            that.banner.style.top = windowHeight - targetBannerAdHeight;
        });
    }

    private _loadGrid() {
        let that = this;
        if (this.gridAd) {
            this.gridAd.destroy();
            this.gridAd = null;
        }
        const { windowWidth, windowHeight } = globalThis.wx.getSystemInfoSync();
        const targetBannerAdWidth = 350;
        const targetBannerAdHeight = 100;
        // 创建格子广告实例，提前初始化
        this.gridAd = globalThis.wx.createCustomAd({
            adUnitId: that._gridId,
            adTheme: 'white',
            gridCount: 5,
            style: {
                width: targetBannerAdWidth,
                height: targetBannerAdHeight,
                left: (windowWidth - targetBannerAdWidth) / 2,
                top: windowHeight - targetBannerAdHeight,
            }
        })
        this.gridAd.onLoad(() => {
            that._bannerLoaded = true;
            // that.gridAd.show();
            setTimeout(() => {
                that._loadGrid();
            }, 60000);
        });
        this.gridAd.onError(() => {
            that._bannerLoaded = false;
            that._loadBanner();
        });
    }

    public showBanner() {
        try {
            if (Math.random() < 0.5) {
                if (this.banner) {
                    this.banner.show();
                } else {
                    if (this.gridAd) {
                        this.gridAd.show();
                    }
                }
            } else {
                if (this.gridAd) {
                    this.gridAd.show();
                } else {
                    if (this.banner) {
                        this.banner.show();
                    }
                }
            }
        } catch (error) {

        }

    }
    public hideBanner() {
        try {
            if (this.banner) {
                this.banner.hide();
            }
            if (this.gridAd) {
                this.gridAd.hide();
            }
        } catch (error) {

        }
    }

    public setKeepScreenOn(options) {
        globalThis.wx.setKeepScreenOn(options);
    }

    public login(options) {
        let that = this;
        console.log("微信登录");
        // globalThis.wx.login({
        //     force: options.force,
        //     success(res) {
        //         console.log(`login调用成功`, res);
        //         let userCode: string = res.code;
        //         let visitorCode: string = res.anonymousCode;
        //         let isLogin: boolean = res.isLogin;
        //         if (isLogin) {
        //             globalThis.wx.getUserInfo({
        //                 success(res) {
        //                     let userJson = JSON.stringify(res.userInfo);
        //                     let data = {
        //                         code: userCode,
        //                         json: userJson,
        //                         visitor: false
        //                     };
        //                     that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
        //                         let result = res.data;
        //                         if (result.user.status == 0) {
        //                             console.log("登录完成，准备回调");
        //                             options.success(result);
        //                         } else {
        //                             console.log("用户状态异常");
        //                             options.fail("你因违规操作,帐号已被系统冻结");
        //                         }
        //                     }, (res) => {
        //                         console.log(`request调用失败`, res);
        //                         options.fail("网络繁忙,请稍后再试");
        //                     })
        //                 },
        //                 fail(res) {
        //                     console.log(`getUserInfo 调用失败`, res);
        //                     //游客登录
        //                     let data = {
        //                         code: visitorCode,
        //                         json: "{}",
        //                         visitor: true
        //                     };
        //                     that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
        //                         let result = res.data;
        //                         if (result.user.status == 0) {
        //                             console.log("登录完成，准备回调");
        //                             options.success(result);
        //                         } else {
        //                             console.log("用户状态异常");
        //                             options.fail("你因违规操作,帐号已被系统冻结");
        //                         }
        //                     }, (res) => {
        //                         console.log(`request调用失败`, res);
        //                         options.fail("网络繁忙,请稍后再试");
        //                     });
        //                 },
        //             });
        //         } else {
        //             //游客登录
        //             let data = {
        //                 code: visitorCode,
        //                 json: "{}",
        //                 visitor: true
        //             };
        //             that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
        //                 let result = res.data;
        //                 if (result.user.status == 0) {
        //                     console.log("登录完成，准备回调");
        //                     options.success(result);
        //                 } else {
        //                     console.log("用户状态异常");
        //                     options.fail("你因违规操作,帐号已被系统冻结");
        //                 }
        //             }, (res) => {
        //                 console.log(`request调用失败`, res);
        //                 options.fail("网络繁忙,请稍后再试");
        //             });
        //         }
        //     },
        //     fail(res) {
        //         console.log(`login调用失败`, res);
        //         options.fail("登录失败,请稍后再试");
        //     },
        // });
    }

    createMoreGamesButton(options) {
        if (this._moreGameBtn) {
            return;
        }
        console.log("创建更多游戏");
        this._moreGameBtn = globalThis.wx.createMoreGamesButton({
            type: "image",
            image: "images/moregame.png",
            style: {
                left: options.left,
                top: options.top,
                width: options.width,
                height: options.height,
                lineHeight: 49,
                backgroundColor: "#00000000",
                textColor: "#ffffff",
                textAlign: "center",
                fontSize: 16,
                borderRadius: 4,
                borderWidth: 1,
                borderColor: "#00000000"
            },
            appLaunchOptions: [],
            onNavigateToMiniGame(res) {
                console.log("跳转其他小游戏", res);
            }
        });
        this._moreGameBtn.onTap(() => {
            console.log("点击更多游戏");
        });
    }

    getOpenDataContext() {
        return globalThis.wx.getOpenDataContext();
    }

    postMessage(msg) {
        console.log("推送开放数据", msg);
        const openCtx = globalThis.wx.getOpenDataContext();
        openCtx.postMessage(msg);
    }

    startRecorder() {
        if (!this._recorder || this._isRecorder) {
            return;
        }
        console.log("准备开始录屏");
        this._recorderTime = new Date().getTime();
        this._isRecorder = true;
        this._recorder.start({
            duration: 60
        });
        cc.game.emit(SDKEvent.CHANGE_RECORDER_STATE);
    }

    stopRecorder(shareFunc?: Function) {
        if (!this._recorder || !this._isRecorder) {
            return;
        }
        console.log("准备停止录屏");
        this._recorderEndTime = new Date().getTime();
        this._recorderShareFunc = shareFunc;
        this._recorder.stop();
        this._isRecorder = false;
        cc.game.emit(SDKEvent.CHANGE_RECORDER_STATE);
    }
    getRecorderTime() {
        return this._recorderEndTime - this._recorderTime;
    }

    getIsScreenRecordVideo() {
        return false;
    }

    getRecorderState() {
        return this._isRecorder;
    }
    public showShareBtn(type: number) {
        let recorderTime = this.getRecorderTime();
        let { windowWidth, windowHeight } = globalThis.wx.getSystemInfoSync();
        if (type == 1) {
            this.shareBtn.style.top = windowHeight - 250;
        } else {
            this.shareBtn.style.top = windowHeight - 200;
        }
        this.shareBtn.share.timeRange = [[0, recorderTime]];
        this.shareBtn.show();
    }
    public hideShareBtn() {
        this.shareBtn.hide();
    }
    shareRecorder(options) {
        let that = this;
        let query = "";
        globalThis.wx.shareAppMessage({
            channel: "video",
            title: that._shareTitle,
            desc: that._shareDesc,
            templateId: that._shareId, // 替换成通过审核的分享ID
            query: query,
            success(res) {
                console.log("分享视频成功");
                options.success && options.success(res.videoId);

            },
            fail(e) {
                console.log("分享视频失败", e);
                options.fail && options.fail(e);
            },
            complete() {

            }
        });
    }

    public showRewardVideo(options: { success: Function, fail: Function }) {
        let that = this;
        that._videoOptions = options;
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) {
            that._videoOptions && that._videoOptions.success && that._videoOptions.success();
            that.sendEvent({ key: "playVideoSuccess" });
            return;
        }

        that._videoAd.show().then(() => {

        }).catch(err => {
            // 可以手动加载一次
            that._videoAd.load().then(() => {
                // 加载成功后需要再显示广告
                return that._videoAd.show();
            });
        });
    }

    setClipboardData(options) {
        globalThis.wx.setClipboardData({
            data: options.data,
            success(res) {
                options.success && options.success();
                console.log("调用剪切板成功", options.data);
            },
            fail(res) {
                options.fail && options.fail();
                console.log("调用剪切板失败", options.data);
            }
        });
    }

    getVideoState() {
        return this._videoLoaded;
    }

    //显示插屏广告
    playScreen() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        let that = this;
        let now = new Date().getTime();
        if (now - this.lastAdTime > 0) {
            if (that._interstitiaAd && that.screenShow) {
                try {
                    that._interstitiaAd.destroy();
                    that._interstitiaAd = null;
                } catch (error) {
                    console.log("销毁插屏广告失败", error);
                }
            }
            if (that._interstitiaAd && !that.screenShow) {
                that._interstitiaAd.load();
            } else {
                console.log("插屏不存在或已经播放，重新创建");
                that._interstitiaAd = globalThis.wx.createInterstitialAd({
                    adUnitId: that._screenId,
                });
                that._interstitiaAd.onLoad(() => {
                    console.log("插屏广告加载成功");
                    that._interstitiaAd.show().then(() => {
                        console.log("插屏广告展示成功");
                        that.screenShow = true;
                        that.lastAdTime = new Date().getTime();
                    });
                });
                that._interstitiaAd.onError((res) => {
                    console.log("插屏广告加载失败", res);
                    that.screenShow = false;
                });
            }
        }
    }

    sendEvent(options) {
        if (!options || !options.key) {
            return;
        }
        console.log("上报事件:", options.key);
        if (options.value) {
            globalThis.wx.reportAnalytics(options.key, options.value);
        } else {
            globalThis.wx.reportAnalytics(options.key, {});
        }
    }

    public vibrateShort() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        if (this._shakeState) return;
        let now = new Date().getTime();
        if (now - this.lastshockTime > 100) {
            this.lastshockTime = now;
            globalThis.wx.vibrateShort({
                success(res) { },
                fail(res) {
                    console.log(`vibrateShort调用失败`);
                }
            });
        }
    }

    public vibrateLong() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        if (this._shakeState) return;
        globalThis.wx.vibrateLong({
            success(res) { },
            fail(res) {
                console.log(`vibrateLong调用失败`);
            }
        });
    }

    public getShakeState(): boolean {
        return this._shakeState;
    }

    public setShakeState(bool: boolean) {
        this._shakeState = bool;
    }


    showToast(content) {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        globalThis.wx.showToast({
            title: content,
            icon: "none",
            duration: 2000,
            success(res) {
            },
            fail(res) {
            },
        });
    }


    setLocalStorage(key, value) {
        cc.sys.localStorage.setItem(key, value);
    }

    getLocalStorage(key) {
        return cc.sys.localStorage.getItem(key);
    }

    sendHttpRequest(url, data, successBack, failBack) {
        globalThis.wx.request({
            url: url,
            data: data,
            success(res) {
                console.log(`request调用成功 `, res);
                if (res.data.ok) {
                    if (successBack) {
                        let result = res.data;
                        successBack(result);
                    }
                } else {
                    if (failBack) {
                        failBack(res.data.msg);
                    }
                }
            },
            fail(res) {
                console.log(`request调用失败`, res);
                if (failBack) {
                    failBack("网络繁忙,请稍后再试");
                }
            },
        });
    }

    contentSafe(options) {
        let data = { text: options.content };
        // this.sendHttpRequest(Common.contentSafeWX, data, (res) => {
        //     if (res.valid) {
        //         options.callBack(true);
        //     } else {
        //         options.callBack(false);
        //     }
        // }, (res) => {
        //     options.callBack(false);
        // })
    }

    //分包
    public wxSubpackage(name: string, callback?: Function) {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) return;
        globalThis.wx.loadSubpackage({
            name: name, // name 可以填 name 或者 root
            success: (res) => {
                // 分包加载成功后通过 success 回调
                callback && callback(true, res);
            },
            fail: (res) => {
                // 分包加载失败通过 fail 回调
                callback && callback(false, res);
            }
        })
    }
};